package cn.bby.query.base.aop;

import cn.bby.jtk.base.constant.CommonErrorCode;
import cn.bby.jtk.web.CommonResult;
import cn.bby.query.base.ann.QueryInterface;
import cn.bby.query.base.constant.QueryAction;
import cn.bby.query.base.model.req.DoQueryReq;
import cn.bby.query.base.model.req.QueryRequest;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Value;

/**
 * @author ben
 * @since 2025/6/8 22:26
 */
@Slf4j
@Aspect
public class AdvQueryInterfaceAop {
    @Value("${query.service.path:http://localhost:10001/QuerySever/DoQuery}")
    private String queryServicePath;

    @Value("${spring.application.name:default}")
    private String applicationName;

    @Around("@annotation(queryInterface)")
    public Object query(ProceedingJoinPoint pjp, QueryInterface queryInterface) throws Throwable {
        Object[] args = pjp.getArgs();
        if (args.length != 1 || !(args[0] instanceof QueryRequest request)) {
            log.warn("高级查询入参必须是 QueryRequest");
            return pjp.proceed();
        }
        // 返回类
        Class<?> returnType = pjp.getSignature().getDeclaringType();
        if (!CommonResult.class.isAssignableFrom(returnType)) {
            log.warn("返回类必须是 QueryResponse");
            return pjp.proceed();
        }
        if (!QueryAction.FAST.equals(request.getAction())) {
            return pjp.proceed();
        }
        HttpRequest post = HttpUtil.createPost(queryServicePath);
        DoQueryReq req = new DoQueryReq();
        req.setRequest(request);
        req.setServiceName(applicationName);
        req.setInterfaceName(queryInterface.name());
        post.body(JSONUtil.toJsonStr(req));
        post.contentType(ContentType.JSON.getValue());
        post.timeout(10000);
        try (HttpResponse response = post.execute()) {
            if (!response.isOk()) {
                log.error("请求查询服务失败: {}", response.body());
                return pjp.proceed();
            }

            CommonResult<JSONObject> result = JSON.parseObject(response.body(), new TypeReference<>() {
            });
            if (ObjectUtil.equals(result.getCode(), CommonErrorCode.SUCCESS)) {
                return result;
            }
        } catch (Exception e) {
            log.error("请求查询服务异常: {}", e.getMessage());
        }
        return pjp.proceed();
    }
}
